<?php

namespace Admin\Controller;
use Think\Model;

/**
 * 管理员操作类
 */
class UserController extends AdminCommonController
{
    /**
     * 用户列表
     */
    public function index()
    {
        $list = M('user')->where(array('del_flg' => 0))
                         ->select();
//                         ->join('as a left join pro_role_user b on a.id = b.user_id')
//                         ->where(array('a.del_flg' => 0))
        if ($list) {
//            foreach($list as $key => &$val) {
//                $val['role'] = M('role')->where(array('id'=>$val['role_id']))->getField('name');
//            }
            $this->assign('user_info' ,$list);
        }
        $this->display();
    }

    /**
     * 详情
     */
    public function detail()
    {
        $id = I('id');
        $flg = $this->checkUserAvailable($id);
        if (!$flg) {
            $this->redirect('/Public/error-500');
        }
        $info = M('user')->getById($id);

        $this->assign('info', $info)
             ->display();
    }

    /**
     * 修改资料
     */
    public function modifyUserInfo()
    {
        $user_info = $this->getUserInfo();
        $model = M('user');
        $list = $model->where(array('id' => $user_info['id']))->find();
        if ($list) {
            $this->assign('user_info', $list)
                 ->display();
        } else {
            $this->redirect('/Public/login');
        }
    }

    /**
     * 修改资料处理
     */
    public function doModifyUserInfo()
    {
        $id        = I('id');
        $email     = I('email');
        $username  = I('username');
        $telephone = I('telephone');

        if ($email && $username && $telephone) {
            $data = array(
                'email'     => $email,
                'username'  => $username,
                'telephone' => $telephone
            ); 
            $res = M('user')->where(array('id' => $id))->save($data);
            if ($res !== false) {
                $code = self::SUCCESS_CODE;
                $message = '修改成功';
                $this->showMessage(array(), $code, $message);
            } else {
                $code = self::ERROR_MSG;
                $message = '修改成功';
                $this->showMessage(array(), $code, $message);
            }
        } else {
            $code = self::ERROR_MSG;
            $message = '参数错误';
            $this->showMessage(array(), $code, $message);
        }
    }

    /**
     * 修改密码
     */
    public function modifyPassword()
    {
        $user_info = $this->getUserInfo();
        $model = M('user');
        $list = $model->where(array('id' => $user_info['id']))->find();
        if ($list) {
            $this->assign('user_info' ,$list)
                 ->display();
        } else {
            $this->redirect('/Public/login');
        }
    }

    /**
     * 修改密码处理
     */
    public function doModifyPassword()
    {
        $id           = I('id');
        $old_password = I('old_password');
        $password     = I('password');
        $password2    = I('password2');

        if ($old_password && $password && $password2) {
            $model = M('user');
            $res = $model->where(array('id' => $id, 'password' => cryptString($old_password)))->find();
            if (!$res) {
                $code = self::SUCCESS_CODE;
                $message = '原密码错误';
                $this->showMessage(array(), $code, $message);
            }
            $data = array(
                'password' => cryptString($password)
            );
            $res2 = $model->where(array('id' => $id))->save($data);
            $content = '新密码:' . $password . ' 请妥善保管!';
            sendMail($res['email'], '密码修改成功', $content);

            if ($res2 !== false) {
                $code = self::SUCCESS_CODE;
                $message = '修改成功';
                $this->showMessage(array(), $code, $message);
            } else {
                $code = self::ERROR_MSG;
                $message = '修改失败';
                $this->showMessage(array(), $code, $message);
            }
        } else {
            $code = self::ERROR_MSG;
            $message = '参数错误';
            $this->showMessage(array(), $code, $message);
        }
    }

    /**
     * 添加用户
     */
    public function add()
    {
        $role = M('role')->select();
        $this->assign('role', $role)
             ->display();
    }

    /**
     * 添加用户处理
     */
    public function doAddUser()
    {
        $account   = I('account');
        $email     = I('email');
        $username  = I('username');
        $telephone = I('telephone');
        $role_id   = I('role_id');

        if ($account && $email && $username && $telephone && $role_id) {
            if (!$this->checkUsername($account)) {
                $code = self::ERROR_MSG;
                $message = '该用户已存在';
                $this->showMessage(array(), $code, $message);
            }
            // 用户表
            $data1 = array(
                'account'     => $account,
                'email'       => $email,
                'username'    => $username,
                'telephone'   => $telephone,
                'password'    => cryptString(C('INIT_PASSWORD')),
                'addtime'     => time(),
                'operator_id' => $this->getOperatorId()
            );
            M()->startTrans();
            $res1 = M('user')->add($data1);
            $data2 = array(
                'role_id' => $role_id,
                'user_id' => $res1,
            );
            $res2 = M('role_user')->add($data2);
            if ($res1 && $res2) {
                M()->startTrans();
                $code  = self::SUCCESS_CODE;
                $message = '添加成功';
                $this->showMessage(array(), $code, $message);
            } else {
                M()->rollback();
                $code = self::ERROR_MSG;
                $message = '添加失败';
                $this->showMessage(array(), $code, $message);
            }
        } else {
            $code = self::ERROR_MSG;
            $message = '参数错误';
            $this->showMessage(array(), $code, $message);
        }
    }

    /**
     * 编辑用户
     */
    public function edit()
    {
        $user_id = I('user_id');
        $role_id = I('role_id');

        $user = M('user')->where(array('id' => $user_id))->find();
        $role = M('role')->select();

        $this->assign('user_info', $user)
             ->assign('role_id', $role_id)
             ->assign('role', $role)
             ->display();
    }

    /**
     * 编辑用户处理
     */
    public function doEditUser()
    {
        $user_id   = I('id');
        $email     = I('email');
        $username  = I('username');
        $telephone = I('telephone');
        $role_id   = I('role_id');

        if ($username && $email && $telephone && $role_id) {
            // 更新管理员
            $data = array(
                'email'       => $email,
                'username'    => $username,
                'telephone'   => $telephone,
                'operator_id' => $this->getOperatorId()
            );
            M()->startTrans();
            $res1 = M('user')->where(array('id' => $user_id))->setField($data);
            // 更新权限
            $res2 = M('role_user')->where(array('user_id' => $user_id))->delete();

            $data3 = array(
                'role_id' => $role_id,
                'user_id' => $user_id,
            );
            $res3 = M('role_user')->add($data3);

            if ($res1 !== false && $res2 && $res3) {
                M()->commit();
                $code  = self::SUCCESS_CODE;
                $message = '编辑成功';
                $this->showMessage(array(), $code, $message);
            } else {
                M()->rollback();
                $code = self::ERROR_MSG;
                $message = '编辑失败';
                $this->showMessage(array(), $code, $message);
            }
        } else {
            $code = self::ERROR_MSG;
            $message = '参数错误';
            $this->showMessage(array(), $code, $message);
        }
    }

    /**
     * 启用或禁用用户
     */
    public function resumeRole()
    {
        $id = I('get.rid',0, 'int');
        $db = M('role');
        $status = $db->where("id = $id")->getField('status');
        $status = ($status == 1)? 0 : 1 ;
        if($db->where("id = $id")->setField('status', $status)){
            $this->ajaxReturn(array(
                'statusCode' => 1,
                'message' => '操作成功',
                'navTabId' =>$_GET['navTabId']
            ));
        } else {
            $this->ajaxReturn(array(
                'statusCode' => 0,
                'message' => '操作失败'
            ));
        }
    }

    /**
     * 用户名校验
     *
     * @param $account
     * @return bool
     */
    protected function checkUsername($account)
    {
        if (!$account) {
            return false;
        }
        $list = M('user')->where(array('account' => $account))->find();
        if ($list) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 用户校验
     *
     * @param $id
     * @return bool
     */
    protected function checkUserAvailable($id)
    {
        if (!$id) {
            return false;
        }
        $list = M('user')->where(array('id' => $id))->find();
        if (!$list) {
            return false;
        } else {
            return true;
        }
    }
}